package com.cooud.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.cooud.order.bean.Order;
import com.cooud.order.feign.ProductFeignClient;
import com.cooud.order.service.OrderService;
import com.cooud.product.bean.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: DongGuoZhen
 * @Date: 2025/03/12/20:00
 * @Description:
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProductFeignClient productFeignClient;


//    标注在非web接口上，违反了流控规则，如果没有指定任何的兜底回调，则会将异常抛出，如果指定了兜底回调，则会调用指定的兜底回调方法，
    @SentinelResource(value = "createOrder",blockHandler = "createOrderFallback") // 定义资源
    @Override
    public Order createOrder(Long productId, Long userId) {
//        Product productFromRemote = getProductFromRemoteLoadBalancer1(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setUserId(userId);
        order.setAddress("xxxxx");
        order.setNickName("xxxx123");
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
        order.setProductList(Arrays.asList(product));
        return order;
    }
//    违反了流控规则，兜底回调方法
    public Order createOrderFallback(Long productId, Long userId, BlockException e) {
        Order order = new Order();
        order.setUserId(userId);
        order.setAddress("xxxxx" + e.getClass());
        order.setNickName("xxxx123");
        order.setTotalAmount(new BigDecimal(0));
        return order;
    }

    private Product getProductFromRemote(Long productId) {
        Product product = null;
        // todo 远程调用商品服务，获取商品信息

        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance serviceInstance = instances.get(0);
        String url = "http://"+serviceInstance.getHost()+":" + serviceInstance.getPort() + "/product/"+ productId;
        log.info("url:{}",url);
        product = restTemplate.getForObject(url, Product.class);
        return product;
    }

//    负载均衡
    private Product getProductFromRemoteLoadBalancer(Long productId) {
        Product product = null;
        //      自动从nacos中获取服务名，并通过负载均衡算法选择一个服务实例
        ServiceInstance instances = loadBalancerClient.choose("service-product");
        String url = "http://"+instances.getHost()+":" + instances.getPort() + "/product/"+ productId;
        log.info("url:{}",url);
        product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    //    基于注解的负载均衡
    private Product getProductFromRemoteLoadBalancer1(Long productId) {
        Product product = null;
//      自动从nacos中获取服务名，并通过负载均衡算法选择一个服务实例 动态的将服务名替换为具体的ip和端口
        String url = "http://service-product/product/"+ productId;
        log.info("url:{}",url);
        product = restTemplate.getForObject(url, Product.class);
        return product;
    }

//    注册中心宕机，远程调用是否成功？
//    1：注册中心宕机，远程调用成功与否的关键在于在注册中心宕机之前是否进行调用，如果进行了调用，那么会将调用的服务信息缓存到本地，即使注册中心宕机，也不会影响远程调用
//    2：如果在注册中心宕机之前没有进行调用，那么远程调用将失败，因为无法找到可用的服务实例
}
